<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>作文文生图 - 作文纸生成器</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      body {
        font-family: "Microsoft YaHei", Arial, sans-serif;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        min-height: 100vh;
        padding: 20px;
      }

      .container {
        max-width: 1400px;
        margin: 0 auto;
        background: white;
        border-radius: 15px;
        box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
        overflow: hidden;
      }

      .header {
        background: linear-gradient(45deg, #4caf50, #45a049);
        color: white;
        padding: 30px;
        text-align: center;
      }

      .header h1 {
        font-size: 2.5em;
        margin-bottom: 10px;
        text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
      }

      .header p {
        font-size: 1.1em;
        opacity: 0.9;
      }

      .input-section {
        padding: 30px;
        background: #f8f9fa;
      }

      .form-row {
        display: flex;
        gap: 20px;
        margin-bottom: 20px;
      }

      .form-group {
        margin-bottom: 25px;
      }

      .form-group.flex-1 {
        flex: 1;
      }

      .form-group label {
        display: block;
        margin-bottom: 8px;
        font-weight: bold;
        color: #333;
        font-size: 1.1em;
      }

      .form-group input {
        width: 100%;
        padding: 12px 15px;
        border: 2px solid #ddd;
        border-radius: 8px;
        font-size: 16px;
        transition: border-color 0.3s;
      }

      .form-group input:focus {
        outline: none;
        border-color: #4caf50;
        box-shadow: 0 0 0 3px rgba(76, 175, 80, 0.1);
      }

      .form-group textarea {
        width: 100%;
        padding: 15px;
        border: 2px solid #ddd;
        border-radius: 8px;
        font-size: 16px;
        line-height: 1.6;
        resize: vertical;
        min-height: 200px;
        font-family: inherit;
        transition: border-color 0.3s;
      }

      .form-group textarea:focus {
        outline: none;
        border-color: #4caf50;
        box-shadow: 0 0 0 3px rgba(76, 175, 80, 0.1);
      }

      .generate-btn {
        background: linear-gradient(45deg, #4caf50, #45a049);
        color: white;
        border: none;
        padding: 15px 40px;
        font-size: 18px;
        border-radius: 25px;
        cursor: pointer;
        transition: all 0.3s;
        box-shadow: 0 4px 15px rgba(76, 175, 80, 0.3);
        display: block;
        margin: 0 auto;
      }

      .generate-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(76, 175, 80, 0.4);
      }

      .generate-btn:active {
        transform: translateY(0);
      }

      .output-section {
        padding: 30px;
        background: white;
      }

      .output-section h2 {
        text-align: center;
        margin-bottom: 30px;
        color: #333;
        font-size: 1.8em;
      }

      .pages-container {
        display: flex;
        flex-wrap: wrap;
        gap: 20px;
        justify-content: center;
      }

      .page-canvas {
        border: 2px solid #ddd;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        background: white;
      }

      .loading {
        text-align: center;
        padding: 40px;
        color: #666;
        font-size: 1.2em;
      }

      .loading::after {
        content: "";
        display: inline-block;
        width: 20px;
        height: 20px;
        border: 3px solid #f3f3f3;
        border-top: 3px solid #4caf50;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-left: 10px;
      }

      @keyframes spin {
        0% {
          transform: rotate(0deg);
        }
        100% {
          transform: rotate(360deg);
        }
      }

      .download-section {
        text-align: center;
        margin-top: 20px;
      }

      .download-btn {
        background: linear-gradient(45deg, #2196f3, #1976d2);
        color: white;
        border: none;
        padding: 12px 30px;
        font-size: 16px;
        border-radius: 20px;
        cursor: pointer;
        margin: 0 10px;
        transition: all 0.3s;
        box-shadow: 0 4px 15px rgba(33, 150, 243, 0.3);
      }

      .download-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(33, 150, 243, 0.4);
      }

      @media (max-width: 768px) {
        .container {
          margin: 10px;
          border-radius: 10px;
        }

        .header {
          padding: 20px;
        }

        .header h1 {
          font-size: 2em;
        }

        .input-section,
        .output-section {
          padding: 20px;
        }

        .form-row {
          flex-direction: column;
        }

        .pages-container {
          flex-direction: column;
          align-items: center;
        }
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="header">
        <h1>📝 作文纸生成器</h1>
        <p>将您的作文转换为标准作文纸格式图片</p>
      </div>

      <div class="input-section">
        <div class="form-row">
          <div class="form-group flex-1">
            <label for="className">班级：</label>
            <input
              type="text"
              id="className"
              placeholder="请输入班级"
              value="高一班"
            />
          </div>
          <div class="form-group flex-1">
            <label for="studentName">姓名：</label>
            <input
              type="text"
              id="studentName"
              placeholder="请输入姓名"
              value="黄雨"
            />
          </div>
          <div class="form-group flex-1">
            <label for="studentId">学号：</label>
            <input
              type="text"
              id="studentId"
              placeholder="请输入学号"
              value="20023"
            />
          </div>
        </div>

        <div class="form-group">
          <label for="title">作文标题：</label>
          <input
            type="text"
            id="title"
            placeholder="请输入作文标题"
            value="陪伴"
          />
        </div>

        <div class="form-group">
          <label for="content">作文内容：</label>
          <textarea id="content" placeholder="请输入作文内容，每段用换行分隔">
每个人的成长都离不开赔伴，在我的成长过程中，是妈妈一直陪伴着我。
记得在一个周末，我在房间里写作业，妈妈在做家务。记得那天的作业很多、很难，我写得头都快炸了，妈妈闻声走了进来，她并没有朝我发火，而是坐在了我旁边，和声细语地给讲题，即使她讲了很多遍我还没听懂，她也不会失去耐心，而是仔细地讲，直到我听懂为止。
在我心里，妈妈是个无所不能的女强人。她什么都会，有时是司机，接送我和妹妹上下学，有时是厨师，给我们一家人做饭；有是保姆，打看家里的卫生。妈妈无所不能，我认为她永远都不会倒下。
这天下着大雨，我发烧了，爸爸又不再家，妈妈只好背着我去医院。我住院了，妈妈拖着疲惫的身体照顾我，经过妈妈的照料，我没过几天就康复出院了。就在我出院这天，妈妈却倒下了，这次挨我来照顾妈妈。
我趴在床边看她，竟发现岁月磨平了妈妈的鬓角，无数的操劳使皱纹爬满她的脸，白头发数都数不清。这一刻，我留下了心疼的泪水。
我想对妈妈说："您辛苦了，谢谢您在这十二年里给予的陪伴，您要对自己好一点，少做一点家务。"</textarea
          >
        </div>

        <button class="generate-btn" onclick="generateCompositionPaper()">
          🎨 生成作文纸
        </button>
      </div>

      <div class="output-section">
        <h2>📄 生成的作文纸</h2>
        <div id="loading" class="loading" style="display: none">
          正在生成作文纸，请稍候...
        </div>
        <div class="pages-container" id="pagesContainer"></div>
        <div
          class="download-section"
          id="downloadSection"
          style="display: none"
        >
          <button class="download-btn" onclick="downloadAllPages()">
            📥 下载作文纸图片
          </button>
        </div>
      </div>
    </div>

    <script>
      // 作文纸配置
      const PAPER_CONFIG = {
        width: 800, // 画布宽度（增加以适应更真实的比例）
        height: 1100, // 画布高度（A4比例）
        cols: 20, // 横向格子数（参考图片调整）
        rows: 22, // 竖向行数（增加行数以容纳更多内容）
        margin: 50, // 边距
        topMargin: 90, // 顶部边距（为信息栏留空间）
        lineWidth: 1, // 线条宽度
        fontSize: 18, // 字体大小
        fontFamily: "SimSun, serif", // 字体
        lineColor: "#000", // 格线颜色（改为黑色更接近真实）
        textColor: "#000", // 文字颜色
        titleColor: "#000", // 标题颜色
        titleFontSize: 20, // 标题字体大小
        infoFontSize: 14, // 信息栏字体大小
      };

      let generatedCanvases = [];

      function generateCompositionPaper() {
        const className = document.getElementById("className").value.trim();
        const studentName = document.getElementById("studentName").value.trim();
        const studentId = document.getElementById("studentId").value.trim();
        const title = document.getElementById("title").value.trim();
        const content = document.getElementById("content").value.trim();

        if (!title || !content) {
          alert("请输入作文标题和内容！");
          return;
        }

        // 显示加载状态
        document.getElementById("loading").style.display = "block";
        document.getElementById("pagesContainer").innerHTML = "";
        document.getElementById("downloadSection").style.display = "none";

        // 延迟执行以显示加载动画
        setTimeout(() => {
          try {
            const pages = createCompositionPages(
              className,
              studentName,
              studentId,
              title,
              content
            );
            displayPages(pages);
            document.getElementById("loading").style.display = "none";
            document.getElementById("downloadSection").style.display = "block";
          } catch (error) {
            console.error("生成作文纸时出错:", error);
            alert("生成作文纸时出现错误，请检查输入内容！");
            document.getElementById("loading").style.display = "none";
          }
        }, 500);
      }

      function createCompositionPages(
        className,
        studentName,
        studentId,
        title,
        content
      ) {
        const pages = [];
        generatedCanvases = [];

        // 处理内容，将段落分解
        const paragraphs = content.split("\n").filter((p) => p.trim());
        let allText = "";

        // 第一行添加题目（居中）
        const titleLine =
          "　".repeat(
            Math.max(0, Math.floor((PAPER_CONFIG.cols - title.length) / 2))
          ) + title;
        allText += titleLine + "\n";

        // 添加内容，每段前面加两个空格缩进
        paragraphs.forEach((paragraph) => {
          allText += "　　" + paragraph + "\n";
        });

        // 将文本分页
        const lines = allText.split("\n");
        let currentPage = [];
        let currentLineCount = 0;

        for (let line of lines) {
          if (currentLineCount >= PAPER_CONFIG.rows) {
            pages.push([...currentPage]);
            currentPage = [];
            currentLineCount = 0;
          }

          // 处理长行，自动换行
          if (line.length > PAPER_CONFIG.cols) {
            let remainingText = line;
            while (
              remainingText.length > 0 &&
              currentLineCount < PAPER_CONFIG.rows
            ) {
              const lineText = remainingText.substring(0, PAPER_CONFIG.cols);
              currentPage.push(lineText);
              remainingText = remainingText.substring(PAPER_CONFIG.cols);
              currentLineCount++;

              if (
                remainingText.length > 0 &&
                currentLineCount >= PAPER_CONFIG.rows
              ) {
                pages.push([...currentPage]);
                currentPage = [];
                currentLineCount = 0;
              }
            }
            if (remainingText.length > 0) {
              currentPage.push(remainingText);
              currentLineCount++;
            }
          } else {
            currentPage.push(line);
            currentLineCount++;
          }
        }

        if (currentPage.length > 0) {
          pages.push(currentPage);
        }

        // 为每页创建画布
        return pages.map((pageLines, pageIndex) => {
          return createPageCanvas(
            className,
            studentName,
            studentId,
            title,
            pageLines,
            pageIndex + 1
          );
        });
      }

      function createPageCanvas(
        className,
        studentName,
        studentId,
        title,
        lines,
        pageNumber
      ) {
        const canvas = document.createElement("canvas");
        canvas.width = PAPER_CONFIG.width;
        canvas.height = PAPER_CONFIG.height;
        canvas.className = "page-canvas";

        const ctx = canvas.getContext("2d");

        // 设置背景
        ctx.fillStyle = "#ffffff";
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        // 绘制页面边框
        drawPageBorder(ctx);

        // 绘制信息栏（只在第一页显示）
        if (pageNumber === 1) {
          drawInfoSection(ctx, className, studentName, studentId);
        }

        // 绘制格线
        drawGrid(ctx);

        // 绘制文字
        drawText(ctx, lines, pageNumber);

        // 绘制页码
        drawPageNumber(ctx, pageNumber);

        generatedCanvases.push(canvas);
        return canvas;
      }

      function drawPageBorder(ctx) {
        ctx.strokeStyle = "#000";
        ctx.lineWidth = 2;
        ctx.strokeRect(
          20,
          20,
          PAPER_CONFIG.width - 40,
          PAPER_CONFIG.height - 40
        );

        // 绘制四个角的小方块
        const cornerSize = 15;
        ctx.fillStyle = "#000";
        // 左上角
        ctx.fillRect(20, 20, cornerSize, cornerSize);
        // 右上角
        ctx.fillRect(PAPER_CONFIG.width - 35, 20, cornerSize, cornerSize);
        // 左下角
        ctx.fillRect(20, PAPER_CONFIG.height - 35, cornerSize, cornerSize);
        // 右下角
        ctx.fillRect(
          PAPER_CONFIG.width - 35,
          PAPER_CONFIG.height - 35,
          cornerSize,
          cornerSize
        );
      }

      function drawInfoSection(ctx, className, studentName, studentId) {
        ctx.fillStyle = "#000";
        ctx.font = `${PAPER_CONFIG.infoFontSize}px ${PAPER_CONFIG.fontFamily}`;
        ctx.textAlign = "left";

        const y = 50;
        const leftMargin = 50;

        // 绘制信息栏
        ctx.fillText(`班级：${className}`, leftMargin, y);
        ctx.fillText(`姓名：${studentName}`, leftMargin + 150, y);
        ctx.fillText(`学号：${studentId}`, leftMargin + 280, y);

        // 绘制信息栏下方的分隔线
        ctx.strokeStyle = "#000";
        ctx.lineWidth = 1;
        ctx.beginPath();
        ctx.moveTo(PAPER_CONFIG.margin, 70);
        ctx.lineTo(PAPER_CONFIG.width - PAPER_CONFIG.margin, 70);
        ctx.stroke();
      }

      function drawGrid(ctx) {
        ctx.strokeStyle = PAPER_CONFIG.lineColor;
        ctx.lineWidth = 0.5;

        const startY = PAPER_CONFIG.topMargin;
        const rowSpacing = 3; // 行与行之间的间距
        const cellWidth =
          (PAPER_CONFIG.width - 2 * PAPER_CONFIG.margin) / PAPER_CONFIG.cols;
        const availableHeight =
          PAPER_CONFIG.height -
          startY -
          PAPER_CONFIG.margin -
          70 -
          (PAPER_CONFIG.rows - 1) * rowSpacing;
        const cellHeight = availableHeight / PAPER_CONFIG.rows;

        // 绘制格子（行与行之间有间距，左右无间距）
        for (let row = 0; row < PAPER_CONFIG.rows; row++) {
          const rowY = startY + row * (cellHeight + rowSpacing);

          // 绘制整行的横线（上边线和下边线）
          ctx.beginPath();
          ctx.moveTo(PAPER_CONFIG.margin, rowY);
          ctx.lineTo(PAPER_CONFIG.width - PAPER_CONFIG.margin, rowY);
          ctx.stroke();

          ctx.beginPath();
          ctx.moveTo(PAPER_CONFIG.margin, rowY + cellHeight);
          ctx.lineTo(
            PAPER_CONFIG.width - PAPER_CONFIG.margin,
            rowY + cellHeight
          );
          ctx.stroke();

          // 绘制竖线分隔每个格子
          for (let col = 0; col <= PAPER_CONFIG.cols; col++) {
            const x = PAPER_CONFIG.margin + col * cellWidth;
            ctx.beginPath();
            ctx.moveTo(x, rowY);
            ctx.lineTo(x, rowY + cellHeight);
            ctx.stroke();
          }
        }
      }

      function drawText(ctx, lines, pageNumber) {
        ctx.fillStyle = PAPER_CONFIG.textColor;
        ctx.font = `${PAPER_CONFIG.fontSize}px ${PAPER_CONFIG.fontFamily}`;
        ctx.textAlign = "center";
        ctx.textBaseline = "middle";

        const startY = PAPER_CONFIG.topMargin;
        const rowSpacing = 3; // 行与行之间的间距
        const cellWidth =
          (PAPER_CONFIG.width - 2 * PAPER_CONFIG.margin) / PAPER_CONFIG.cols;
        const availableHeight =
          PAPER_CONFIG.height -
          startY -
          PAPER_CONFIG.margin -
          70 -
          (PAPER_CONFIG.rows - 1) * rowSpacing;
        const cellHeight = availableHeight / PAPER_CONFIG.rows;

        lines.forEach((line, lineIndex) => {
          if (lineIndex >= PAPER_CONFIG.rows) return;

          for (
            let charIndex = 0;
            charIndex < line.length && charIndex < PAPER_CONFIG.cols;
            charIndex++
          ) {
            const char = line[charIndex];
            if (char && char.trim()) {
              const x =
                PAPER_CONFIG.margin + charIndex * cellWidth + cellWidth / 2;
              const y =
                startY + lineIndex * (cellHeight + rowSpacing) + cellHeight / 2;

              // 只有第一页的第一行（题目）使用粗体，其他都使用正常字体
              if (lineIndex === 0 && pageNumber === 1) {
                ctx.font = `bold ${PAPER_CONFIG.titleFontSize}px ${PAPER_CONFIG.fontFamily}`;
                ctx.fillStyle = PAPER_CONFIG.titleColor;
              } else {
                ctx.font = `normal ${PAPER_CONFIG.fontSize}px ${PAPER_CONFIG.fontFamily}`;
                ctx.fillStyle = PAPER_CONFIG.textColor;
              }

              ctx.fillText(char, x, y);
            }
          }
        });
      }

      function drawPageNumber(ctx, pageNumber) {
        ctx.fillStyle = "#000";
        ctx.font = `12px ${PAPER_CONFIG.fontFamily}`;
        ctx.textAlign = "center";
        ctx.fillText(
          `第 ${pageNumber} 页`,
          PAPER_CONFIG.width / 2,
          PAPER_CONFIG.height - 50
        );
      }

      function displayPages(canvases) {
        const container = document.getElementById("pagesContainer");
        container.innerHTML = "";

        // 创建横向排列的合并画布
        const combinedCanvas = document.createElement("canvas");
        const totalWidth = canvases.length * PAPER_CONFIG.width;
        combinedCanvas.width = totalWidth;
        combinedCanvas.height = PAPER_CONFIG.height;
        combinedCanvas.className = "page-canvas";
        combinedCanvas.style.maxWidth = "100%";
        combinedCanvas.style.height = "auto";

        const ctx = combinedCanvas.getContext("2d");
        ctx.fillStyle = "#ffffff";
        ctx.fillRect(0, 0, combinedCanvas.width, combinedCanvas.height);

        // 横向排列每一页
        canvases.forEach((canvas, index) => {
          ctx.drawImage(canvas, index * PAPER_CONFIG.width, 0);
        });

        const pageDiv = document.createElement("div");
        pageDiv.style.textAlign = "center";
        pageDiv.style.marginBottom = "20px";

        const pageTitle = document.createElement("h3");
        pageTitle.textContent = `作文纸 (共 ${canvases.length} 页)`;
        pageTitle.style.marginBottom = "10px";
        pageTitle.style.color = "#666";

        pageDiv.appendChild(pageTitle);
        pageDiv.appendChild(combinedCanvas);

        // 添加下载按钮
        const downloadBtn = document.createElement("button");
        downloadBtn.textContent = "下载作文纸";
        downloadBtn.className = "download-btn";
        downloadBtn.style.marginTop = "10px";
        downloadBtn.onclick = () => downloadCombinedImage(combinedCanvas);
        pageDiv.appendChild(downloadBtn);

        container.appendChild(pageDiv);

        // 更新全局变量以供其他下载函数使用
        generatedCanvases = [combinedCanvas];
      }

      function downloadCombinedImage(canvas) {
        const link = document.createElement("a");
        link.download = "作文纸_完整版.png";
        link.href = canvas.toDataURL();
        link.click();
      }

      function downloadAllPages() {
        // 现在只有一张合并的图片
        if (generatedCanvases.length > 0) {
          downloadCombinedImage(generatedCanvases[0]);
        }
      }

      function downloadAsPDF() {
        // 现在只有一张合并的图片
        if (generatedCanvases.length > 0) {
          downloadCombinedImage(generatedCanvases[0]);
        }
      }

      // 页面加载完成后自动生成示例
      window.addEventListener("load", () => {
        // 可以选择是否自动生成示例
        // generateCompositionPaper();
      });
    </script>
  </body>
</html>
